<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchNum="searchItemCount"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      :showCollapse="false"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="formEname" label="岗位编码">
          <FIInput v-model="state.query.postEname" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="formCname" label="岗位名称">
          <FIInput v-model="state.query.postCname" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="岗位列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="postId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      deletable
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
      @row-delete="deleteRow"
    >
    </FITable>
    <member-set
      :setShow="setShow"
      @get-list="searchFn"
      @update:setShow="(newValue) => (setShow = newValue)"
      :editData="editData"
    ></member-set>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed } from 'vue'
import memberSet from './components/memberSet'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiPostquery, apiPostdelete, apiPostinsert } from '@/api/user'
import { getCurrentInstance } from 'vue'
import { apiRequestPost } from '@/api/globalApi.js'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()

const searchWrapperSpan = 8
const isTableLoading = ref(false)
const editData = ref({})
// 页面编码
const tableId = 'postManage'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const setShow = ref(false)
const state = reactive({
  query: {
    current: 1,
    size: 10,
    postCname: '',
    postEname: '',
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const columns: Column[] = reactive([
  {
    label: '岗位编码',
    prop: 'postEname',
    align: 'center',
    editable: true,
    sortable: false,
    readonly: true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { postEname: [{ required: true, message: '请输入岗位编码', trigger: 'blur' }] },
    },
  },
  {
    label: '岗位名称',
    prop: 'postCname',
    align: 'center',
    queryName: '',
    editable: true,
    sortable: false,
    filterable: false,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { postCname: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }] },
    },
  },
  // {
  //   label: '岗位排序',
  //   prop: 'sortIndex',
  //   align: 'center',
  //   editable: true,
  //   filterable: false,
  //   sortable: false,
  //   modelValue: { inputValue: '' },
  //   editType: 'input',
  // },
  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [{ id: 'openPostUser', type: 'set' }],
  },
  // {
  //   label: '修改人',
  //   prop: 'recRevisor',
  //   align: 'center',
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  // {
  //   label: '修改时间',
  //   prop: 'recReviseTime',
  //   align: 'center',
  //   editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
//操作
const actionClick = (item, rowData, btnInfo) => {
  editData.value = {}
  editData.value = rowData
  if (item.type == 'set') {
    setShow.value = true
  }
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  isTableLoading.value = true
  // const {postEname,postCname} = state.query

  state.query = obj.queryData
  columns.values = obj.columns
  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const par = {
    // current:obj.queryData.current,
    // size:obj.queryData.size,
    // postCname,
    // postEname,
    ...state.query,
  }
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        // pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  for (let i of checkedRows.value) {
    if (!i.postCname) {
      useMessage().warning('请输入岗位名称')
      return
    }
    if (!i.postEname) {
      useMessage().warning('请输入岗位编码')
      return
    }
  }
  isTableLoading.value = true
  saveSuccessful.value = false
  const apiUrl = proxy.$Button_api('save', route.name)
  apiRequestPost(apiUrl, checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
//删除事件
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.postId) ids.push(item?.postId)
    })
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('delete', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      useMessage().error(error.data.message)
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
